#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
using FE;
using Game = FE.Game;
#endregion

namespace WinXnaFE
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        ContentManager content;
        SpriteBatch batch;
        XnaGameAdapter xga;
        SelectCursor cursor;
        Texture2D selectTexture;
        Dictionary<string, UnitAnimation> UnitAnimations = new Dictionary<string, UnitAnimation>();
        
        public SpriteFont TestFont;
        public XnaGameAdapter.GameTask currentTask;

        
        public Game1(XnaGameAdapter xga)
        {            
            this.xga = xga;
            graphics = new GraphicsDeviceManager(this);
            content = new ContentManager(Services, "Media\\");            
        }


        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }


        /// <summary>
        /// Load your graphics content.  If loadAllContent is true, you should
        /// load content from both ResourceManagementMode pools.  Otherwise, just
        /// load ResourceManagementMode.Manual content.
        /// </summary>
        /// <param name="loadAllContent">Which type of content to load.</param>
        protected override void LoadGraphicsContent(bool loadAllContent)
        {
            if (loadAllContent)
            {
                batch = new SpriteBatch(graphics.GraphicsDevice);

                selectTexture = content.Load<Texture2D>("Selector");

                SpriteAnimation assn = new SpriteAnimation(content, "Media\\MaleAssnIdle.anim");
                SpriteAnimation hero = new SpriteAnimation(content, "Media\\HectorIdle.anim");

                //SpriteAnimation heroAttack = new SpriteAnimation(content, "Media\\HectorAttackAxe.anim");

                UnitAnimation monster = new UnitAnimation();
                monster.MapIdle = assn;

                UnitAnimation heroAnims = new UnitAnimation();
                heroAnims.MapIdle = hero;
                //heroAnims.Attack = heroAttack;

                UnitAnimations["Sebastien"] = heroAnims;
                UnitAnimations["Monster One"] = monster;
                UnitAnimations["Monster Two"] = monster;

                xga.SpriteMap[typeof(PlainsTile)] = content.Load<Texture2D>("Grass Block");
                xga.SpriteMap[typeof(MountainsTile)] = content.Load<Texture2D>("Mountains Block");
                xga.SpriteMap[typeof(WoodsTile)] = content.Load<Texture2D>("Woods Block");

                TestFont = content.Load<SpriteFont>("TestFont");

                xga.Start();

                cursor = new SelectCursor(selectTexture, xga.CurrentMap);

            }

            // TODO: Load any ResourceManagementMode.Manual content
        }


        /// <summary>
        /// Unload your graphics content.  If unloadAllContent is true, you should
        /// unload content from both ResourceManagementMode pools.  Otherwise, just
        /// unload ResourceManagementMode.Manual content.  Manual content will get
        /// Disposed by the GraphicsDevice during a Reset.
        /// </summary>
        /// <param name="unloadAllContent">Which type of content to unload.</param>
        protected override void UnloadGraphicsContent(bool unloadAllContent)
        {
            if (unloadAllContent)
            {
                // TODO: Unload any ResourceManagementMode.Automatic content
                content.Unload();
            }

            // TODO: Unload any ResourceManagementMode.Manual content
        }
        public InputBuffer<bool> AButtonBuffer = new InputBuffer<bool>(false, 5000, 5000);
        public InputBuffer<bool> YButtonBuffer = new InputBuffer<bool>(false, 5000, 5000);
        public InputBuffer<bool> XButtonBuffer = new InputBuffer<bool>(false, 5000, 5000);
        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            if (currentTask != null)
            {
                currentTask.Input(GamePad.GetState(xga.CurrentPlayerController), gameTime.ElapsedGameTime.TotalMilliseconds);
                currentTask.Update(gameTime.ElapsedGameTime.TotalMilliseconds);

                if (currentTask.Finished) { currentTask = null; }
            }
            cursor.Input(GamePad.GetState(PlayerIndex.One), gameTime.ElapsedGameTime.TotalMilliseconds);
            AButtonBuffer.Set(GamePad.GetState(PlayerIndex.One).Buttons.A == ButtonState.Pressed, gameTime.ElapsedGameTime.TotalMilliseconds);
            YButtonBuffer.Set(GamePad.GetState(PlayerIndex.One).Buttons.Y == ButtonState.Pressed, gameTime.ElapsedGameTime.TotalMilliseconds);
            XButtonBuffer.Set(GamePad.GetState(PlayerIndex.One).Buttons.X == ButtonState.Pressed, gameTime.ElapsedGameTime.TotalMilliseconds);
            if (AButtonBuffer.HasNewEvent && AButtonBuffer.NewEvent)
            {
                if (xga.CurrentPlayer != null)
                {
                    int cursorPositionX = (int)cursor.position.X;
                    int cursorPositionY = (int)cursor.position.Y;

                    Map.MapNode mn = xga.CurrentMap[cursorPositionX, cursorPositionY];
                    if (mn.unit != null)
                    {
                        if (xga.CurrentPlayer.OwnsUnit(mn.unit))
                        {
                            if (mn.unit == xga.CurrentUnit)
                            {
                                xga.Game.Input(new UnitMoveInput()[cursorPositionX, cursorPositionY]);
                            }
                            xga.Game.Input(new UnitSelectInput()[cursorPositionX, cursorPositionY]);
                        }
                        else
                        {
                            xga.Game.Input(new UnitAttackInput()[cursorPositionX, cursorPositionY]);
                        }
                    }
                    else
                    {
                        xga.Game.Input(new UnitMoveInput()[cursorPositionX, cursorPositionY]);
                    }
                }
            }
            if (YButtonBuffer.HasNewEvent && YButtonBuffer.NewEvent)
            {
                xga.ActionChosen(GameAdapter.Actions.Attack);
            }
            if (XButtonBuffer.HasNewEvent && XButtonBuffer.NewEvent)
            {
                xga.ActionChosen(GameAdapter.Actions.Wait);
            }
            // TODO: Add your update logic here

            base.Update(gameTime);
        }


        public const int tileWidth = 100;
        public const int tileHeight = 85;
        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            graphics.GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here
            batch.Begin();
            Map m = xga.CurrentMap;

            for (int x = 0; x < m.Width; x++)
            {
                for (int y = 0; y < m.Height; y++)
                {
                    Map.MapNode mn = m[x, y];
                    Vector2 pos = new Vector2(x * tileWidth, y * tileHeight);
                    if (xga.SpriteMap.ContainsKey(mn.tile.GetType()))
                    {
                        Color highColor;
                        if (mn.highlightAction == GameAdapter.Actions.Move)
                            highColor = Color.DeepSkyBlue;
                        else if (mn.highlightAction == GameAdapter.Actions.Attack)
                            highColor = Color.Crimson;
                        else
                            highColor = Color.White;
                        batch.Draw(xga.SpriteMap[mn.tile.GetType()], pos, highColor);
                    }
                }
            }
            cursor.Draw(batch, gameTime.ElapsedRealTime.TotalMilliseconds);

            for (int x = 0; x < m.Width; x++)
            {
                for (int y = 0; y < m.Height; y++)
                {
                    Map.MapNode mn = m[x, y];
                    if (mn.unit != null)
                    {
                        Vector2 pos = new Vector2(x * tileWidth, y * tileHeight);
                        pos.Y += 35;
                        UnitAnimation sa = UnitAnimations[mn.unit.unit.Name];
                        sa.MapIdle.Draw(batch, gameTime.ElapsedRealTime.TotalMilliseconds, pos);
                    }
                }
            }

            if (currentTask != null)
            {
                currentTask.Render(graphics.GraphicsDevice, batch, gameTime.ElapsedRealTime.TotalMilliseconds);
            }

            batch.End();

            base.Draw(gameTime);
        }
    }
}
